package test;

import java.sql.*;

public class javaUtil1 {
    private static String driver="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=utf-8";
    private static String username="root";
    private static String password="root";
    private static Connection con=null;
    private static PreparedStatement ps;
    private static ResultSet rs;
//    获取链接
    public static boolean getcon(){
        try {
            Class.forName(driver);
            con= DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
//    增删改
    public  static int excuteUpdate(String sql,Object[] params){
        int updateRows=0; //修改的行数
       if (getcon()==true){
           try {
               PreparedStatement ps=con.prepareStatement(sql);
               for (int i=0;i<params.length;i++){
                   ps.setObject(i+1,params[i]);
               }
               updateRows=ps.executeUpdate();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
        return  updateRows;
    }

//    查
    public static ResultSet excute(String sql,Object[] params){
        ResultSet rs=null;
        if(getcon()){
            try {
                ps=con.prepareStatement(sql);
                for (int i=0;i<params.length;i++){
                    ps.setObject(i+1,params[i]);
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }


//    关闭
   public static void close(){
       if (rs!=null){
           try {
               rs.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if (ps!=null){
           try {
               ps.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
   }
}
